package com.jd.webapp.controller;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.jd.webapp.service.FileService;


@Controller
public class FileController {
	private static final Logger logger =  Logger.getLogger(FileController.class);
	
	@Autowired
	private FileService fileService;
	
	@RequestMapping("/pic/upload")
	public @ResponseBody Object upload(MultipartFile uploadFile){
		Map<String,Object> map = new HashMap<String, Object>();
		//获取输入流对象
		try {
			InputStream inputStream = uploadFile.getInputStream();
			String originalFilename = uploadFile.getOriginalFilename();
			if(logger.isDebugEnabled()){
				String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
				logger.debug("debug-------------->>>上传文件的原始名称:"+originalFilename);
				logger.debug("debug-------------->>>截取上传文件的后缀名称:"+suffix);
			}
			//调用服务上传文件到文件服务器
			String upload = fileService.upload(originalFilename, inputStream);
			if(upload!=null){
				map.put("error", 0);
				map.put("url",upload);
			}else{
				map.put("error", 1);
				map.put("message","上传失败");
			}
		} catch (Exception e) {
			e.printStackTrace();
			map.put("error", 1);
			map.put("message",e.getMessage());
		}
		return map;
	}
}
